package com.wu.example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class Translate extends BaseActivity {

	private static final String TAG = "Translate";

	private EditText txtOriginal = null;
	private Spinner sprFrom = null, sprTo = null;
	private TextView txtTranslated = null, txtRetranslated = null;

	private TextWatcher txtWatcher = null;
	private OnItemSelectedListener itemListener = null;

	private Handler guiThread = null;
	private ExecutorService transThread = null;
	private Runnable updateTask = null;
	private Future transPending = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		initThreading();
		autoFindViewsById();
		setAdapters();
		setListeners();
	}

	private void initThreading() {
		guiThread = new Handler();
		transThread = Executors.newSingleThreadExecutor();
		// This task does a translation and updates the screen
		updateTask = new Runnable() {

			@Override
			public void run() {
				// Get text to translate
				String original = txtOriginal.getText().toString().trim();
				// Cancel previous translation
				if (transPending != null) {
					transPending.cancel(true);
				}
				// Take care of the easy case
				if (original.length() == 0) {
					txtTranslated.setText(R.string.empty);
					txtRetranslated.setText(R.string.empty);
				} else {
					// Let user know we're doing something
					txtTranslated.setText(R.string.translating);
					txtRetranslated.setText(R.string.translating);

					// Begin translation now but don't wait for it
					try {
						// TODO
						// Translate
						// transThread.submit();
					} catch (Exception e) {
						// Unable to start new task
						txtTranslated.setText(R.string.translation_error);
						txtRetranslated.setText(R.string.translation_error);
					}
				}
			}
		};
	}

	private void setListeners() {
		// define event listeners
		txtWatcher = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int count,
					int after) {
				queueUpdate(1000);
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// do noting

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// do noting

			}
		};

		itemListener = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				queueUpdate(200);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// do noting

			}
		};
		// set listeners on graphical user interface widgets
		txtOriginal.addTextChangedListener(txtWatcher);
		sprFrom.setOnItemSelectedListener(itemListener);
		sprTo.setOnItemSelectedListener(itemListener);

	}

	protected void queueUpdate(int delayedTime) {
		// Cancel provious update if it hasn't started yet
		guiThread.removeCallbacks(updateTask);
		// Start an update if nothing happens after a few millisenconds
		guiThread.postDelayed(updateTask, delayedTime);
	}

	private void setAdapters() {
		// spinner list comes from a resource
		// spinner user interface users standard layouts
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.languages, android.R.layout.simple_spinner_item);
		sprFrom.setAdapter(adapter);
		sprTo.setAdapter(adapter);
		// automatically select two spinner items
		sprFrom.setSelection(2); 	
		sprTo.setSelection(1);

	}

	private String getLang(Spinner sprinner) {
		String language = sprinner.getSelectedItem().toString();
		String[] lang = language.split(",");
		if (lang.length == 2) {
			return language.split(",")[1];
		} else {
			return "en";
		}
	}

	/**
	 * Modify text on the screen (called from another thread)
	 * 
	 * @param text
	 */
	public void setTranslated(String text) {
		guiSetText(txtTranslated, text);
	}

	public void setRetranslated(String text) {
		guiSetText(txtRetranslated, text);
	}

	/**
	 * All changes to the GUI must be done in the GUI thread
	 * 
	 * @param txtTranslated2
	 * @param text
	 */
	private void guiSetText(final TextView txtView, final String text) {
		guiThread.post(new Runnable() {

			@Override
			public void run() {
				txtView.setText(text);
			}
		});
	}
}